﻿using System;
using System.ComponentModel;
using System.Reflection;
using System.Windows.Forms;

namespace KD.Sms
{
    public class EnumHelper
    {
        public static string GetEnumDes(object en)
        {
            MemberInfo[] member = en.GetType().GetMember(en.ToString());
            if (member.Length > 0)
            {
                object[] customAttributes = member[0].GetCustomAttributes(typeof(DescriptionAttribute), false);
                if (customAttributes.Length > 0)
                {
                    return ((DescriptionAttribute)customAttributes[0]).Description;
                }
            }
            return en.ToString();
        }

        /// <summary>
        /// 绑定枚举到ComboBox控件
        /// </summary>
        /// <typeparam name="T">枚举</typeparam>
        /// <param name="cboCtrl">ComboBox控件</param>
        /// <param name="selectedIndex">选定ComboBox控件中的项目的序号</param>
        public static void BindEnumToComboxBox<T>(ComboBox cboCtrl, int selectedIndex = 0) where T : struct
        {
            var typeT = typeof(T);
            if (!typeT.IsEnum)
            {
                return;
            }
            var fields = typeT.GetFields();
            if (fields != null && fields.Length > 0)
            {
                foreach (FieldInfo fi in fields)
                {
                    if (fi.FieldType.IsEnum)
                    {
                        cboCtrl.Items.Add(System.Text.RegularExpressions.Regex.Replace(fi.Name, @"\d", "").Replace("A", ""));
                    }
                }
                if (selectedIndex >= 0 && selectedIndex < cboCtrl.Items.Count)
                {
                    cboCtrl.SelectedIndex = selectedIndex;
                }
                else if (cboCtrl.Items.Count > 0)
                {
                    cboCtrl.SelectedIndex = 0;
                }
            }
        }
    }
}
